package com.teachoa.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.teachoa.bean.Order;
import com.teachoa.bean.OrderLog;
import com.teachoa.bean.Project;
import com.teachoa.bean.Task;
import com.teachoa.bean.UserTask;
import com.teachoa.enumtype.ProjectStatusEnum;
import com.teachoa.util.IDUtil;

@SuppressWarnings({"rawtypes", "unchecked"})
public class TaskController extends BaseController {
	
	public void currentTask() {
		String taskId = getPara(0);
		String orderId = getPara(1);
		OrderLog log = OrderLog.dao.findOrderLogsByOIdAndTId(orderId, taskId);
		if(log!=null) {
			Map map = JSON.parseObject(log.getStr("content"));
			map.put("id", log.getStr("id"));
			System.err.println(log);
			int flag = log.getInt("flag");
			if(flag==0) {
				map.put("flag", log.getInt("flag"));
				map.put("opinion", log.getStr("opinion"));
				setAttr("log", map);
			} 
		}
		renderJsp("task.jsp");
	}
	
	@Before(Tx.class)
	public void execute() {
		String taskId = getPara("taskId");
		String orderId = getPara("orderId");
		int node = getParaToInt("node");
		try {
			//提交给老师审核，修改order表status为待审核
			Order order = Order.dao.findById(orderId);
			order.set("status", 2);
			order.update();
			//生成一条log，用于记录提交的任务信息
			OrderLog orderLog = new OrderLog();
			orderLog.set("id", IDUtil.getId());
			orderLog.set("order_id", orderId);
			//orderLog.set("project_id", order.getStr("project_id"));
			orderLog.set("task_id", taskId);
			orderLog.set("node", node);
			orderLog.set("user_id", super.getCurrentUserId());
			orderLog.set("user_name", super.getCurrentUserName());
			orderLog.set("create_time", new Date());
			
			Map map = super.getParamMap();
			map.remove("taskId");
			map.remove("orderId");
			map.remove("node");
			orderLog.set("content", JSON.toJSONString(map));
			orderLog.save();
//			int node = super.getProcessNodeByTaskName(processId, taskName);
//			Project project = Project.dao.getProjectByOrderId(orderId);
//			List<Record> list = UserTask.dao.getUsersByPidAndNode(project.getStr("id"), node);
//			String[] userIds = new String[list.size()];
//			for(int i=0;i<userIds.length;i++) {
//				String userId = list.get(i).getStr("user_id");
//				userIds[i] = userId;
//			}
//			List<Task> taskList = super.getSnakerEngine().executeTask(taskId, super.getCurrentUserId()
//					, Maps.newHashMap(node+"", userIds, node+"-text", text));
//			if(taskList.size()==0) {
//				project.set("status", ProjectStatusEnum.END.getCode());
//				project.update();
//			}
//			System.err.println(taskList.size());
//			for(Task task:taskList) {
//				System.err.println(task.getDisplayName());
//				System.err.println(task.getTaskName());
//			}
			renderJson(success("提交成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("提交失败！！"));
		}
	}
	
	public void processView() {
		String projectId = getPara("projectId");
		Project project = Project.dao.findById(projectId);
		String orderId = project.getStr("order_id");
		List<OrderLog> logs = OrderLog.dao.findOrderLogsByOId(orderId);
		for(OrderLog log:logs) {
			Task task = Task.dao.findById(log.getStr("task_id"));
			log.put("task", task);
			Integer flag = log.getInt("flag");
			String flagDesc = null;
			if(flag==null) flagDesc = "未审核";
			else if(flag==0) flagDesc = "不通过";
			else if(flag==1) flagDesc = "通过";
			log.put("flagDesc", flagDesc);
		}
		setAttr("orderId", orderId);
		setAttr("logs", logs);
		renderJsp("view.jsp");
	}
	
	public void processJson() {
		/*String orderId = getPara("orderId");
		String processId = getPara("processId");
		SnakerEngine se = super.getSnakerEngine();
		List<Task> tasks = se.query().getActiveTasks(new QueryFilter().setOrderId(orderId));
		Process process = se.process().getProcessById(processId);
		ProcessModel model = process.getModel();
		Map<String, String> jsonMap = new HashMap<String, String>();
		if(model != null) {
			jsonMap.put("process", SnakerUtil.getModelJson(model));
		}
		
		//{"activeRects":{"rects":[{"paths":[],"name":"任务3"},{"paths":[],"name":"任务4"},{"paths":[],"name":"任务2"}]},"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}}
		if(tasks != null && !tasks.isEmpty()) {
			jsonMap.put("active", SnakerUtil.getActiveJson(tasks));
		}
		renderJson(JSON.toJSONString(jsonMap));*/
	}
	
	public void auditList() {
		String userId = super.getCurrentUserId();
		Page<Record> page = Order.dao.findAuditTasksByTeacherId(1, userId);
		for(Record record:page.getList()) {
			String taskId = record.getStr("task_id");
			Task task = Task.dao.findById(taskId);
			record.set("task", task);
			//String nodeUserId = record.getStr("user_id");
			//User user = User.dao.findById(nodeUserId);
			//record.set("user", user);
		}
		setAttr("orderPage", page);
		renderJsp("auditList.jsp");
	}
	
	public void load() {
		String orderId = getPara(0);
		String taskId = getPara(1);
		OrderLog log = OrderLog.dao.findOrderLogsByOIdAndTId(orderId, taskId);
		Map map = JSON.parseObject(log.getStr("content"));
		map.put("id", log.getStr("id"));
		setAttr("log", map);
		renderJsp("orderLog.jsp");
	}
	
	@Before(Tx.class)
	public void audit() {
		try {
			int flag = getParaToInt("flag");
			String orderLogId = getPara("id");
			OrderLog orderLog = OrderLog.dao.findById(orderLogId);
			orderLog.set("flag", flag);
			String orderId = orderLog.getStr("order_id");
			
			Order order = Order.dao.findById(orderId);
			if(flag==0) {
				//审核不通过
				orderLog.set("opinion", getPara("opinion"));
				
				//order的status置为1
				order.set("status", 1);
				order.update();
			} else if(flag==1) {
				//order传向下一个节点
				int node = order.getInt("node");
				int newNode = node+1;
				
				String projectId = order.getStr("project_id");
				String flowId = Project.dao.getFlowIdByProjectId(projectId);
				int maxNode = Task.dao.getMaxNodeByProcessId(flowId);
				//判断+1后节点是否大于当前流程最大节点，如果大于project就置为结束
				if(newNode<=maxNode) {
					
					//当前节点共有total个分支
					System.err.println("flowId="+flowId);
					System.err.println("orderId="+orderId);
					System.err.println("node="+node);
					int total = Task.dao.getTotalNumByPidAndNode(flowId, node);
					int total2 = OrderLog.dao.getTotalSuccsByOIdAndNode(orderId, node);
					System.err.println("node总数:"+total);
					System.err.println("成功总数:"+total2);
					if(total-total2==1) {
						order.set("node", newNode);
						order.set("status", 1);
						order.update();
						UserTask.dao.updateCurrentNodeByPidAndNode(projectId, newNode);
					}
				} else {
					Project project = new Project();
					project.set("id", projectId);
					project.set("status", ProjectStatusEnum.END.getCode());
					project.update();
				}
			}
			orderLog.update();
			renderJson(success("提交成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("提交失败！！"));
		}
	}

}
